<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <button @click='$router.push("/home")'>首页</button>
        <button @click='$router.push("/news")'>新闻</button>
        <button @click='$router.push("/about")'>关于</button>
        <router-view></router-view>
    </div>
</body>
<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>
    const originalPush = VueRouter.prototype.push
    VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
  }
    const home={
        template:`
            <div>
                我是home页    
            </div>
        
        `
    };
    const news={
        template:`
            <div>
                我是mews页    
            </div>
        
        `
    };
    const about={
        template:`
            <div>
                我是about页    
            </div>
        
        `
    };
    const login={
        template:`
            <div>
                <span>这是注册页</span>
                <button @click='login'>点击注册</button>    
            </div>
        `,
        methods:{
            login(){
                localStorage.setItem('token','7987987');
                this.$router.replace(this.$route.query.from)
            }
        }
    }
    const router=new VueRouter({
        routes:[
            {
                path:'/',
                redirect:'/home',
                
            },
            {
                path:'/home',
                component:home,
                meta:{
                    needLogn:false
                }
            },
            {
                path:'/news',
                component:news,
                meta:{
                    needLogn:true
                }
            },
            {
                path:'/about',
                component:about,
                meta:{
                    needLogn:true
                }
            },
            {
                path:'/login',
                component:login,
                meta:{
                    needLogn:false
                }
            }
        ]
    })
    const isLogin = () => !!localStorage.getItem('token');
    router.beforeEach((to,from,next)=>{
      if(to.meta.needLogn){
          if(isLogin()){
              next()
          }else{
              next({
                  path:'/login',
                  query:{
                      from:to.path
                  }
              })
          }
      }else{
          next()
      }
        
    })
    const vm=new Vue({
        el:'#app',
        router
    })
</script>
</html>